<template>
  <div class="page-modal">
    <el-dialog
      title=""
      v-model="dialogVisible"
      width="50%"
      center
      destroy-on-close
    >
      <lz-form v-bind="modalConfig" v-model="formData"></lz-form>
      <slot></slot>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleConfirmClick">
            Confirm
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineExpose, watch } from 'vue'
import { useStore } from 'vuex'

import LzForm from '@/base-ui/form'

const props = defineProps({
  modalConfig: {
    type: Object,
    required: true
  },
  defaultInfo: {
    type: Object,
    default: () => ({})
  },
  otherInfo: {
    type: Object,
    default: () => ({})
  },
  pageName: {
    type: String,
    require: true
  },
  storeName: {
    type: String,
    default: 'system'
  }
})

const dialogVisible = ref(false)
const formData = ref<any>({})

watch(
  () => props.defaultInfo,
  (newValue) => {
    for (const item of props.modalConfig.formItems) {
      formData.value[`${item.field}`] = newValue[`${item.field}`]
    }
  }
)

console.log('page modal: ')
// 点击确定按钮的逻辑
const store = useStore()
const handleConfirmClick = () => {
  dialogVisible.value = false
  if (Object.keys(props.defaultInfo).length) {
    // 编辑
    console.log('编辑')
    console.log(props.defaultInfo)
    console.log(formData.value)
    console.log(props.otherInfo)
    store.dispatch(`${props.storeName}/editPageDataAction`, {
      pageName: props.pageName,
      editData: { ...formData.value, ...props.otherInfo },
      id: props.defaultInfo.id
    })
  } else {
    // 新建
    console.log('新建用户')
    store.dispatch(`${props.storeName}/createPageDataAction`, {
      pageName: props.pageName,
      newData: { ...formData.value, ...props.otherInfo }
    })
  }
}

defineExpose({ dialogVisible })
</script>

<style scoped></style>
